//
//  ViewController.swift
//  contactDemo_swift
//
//  Created by 郭颢源 on 2020/8/7.
//  Copyright © 2020 test. All rights reserved.
//

import UIKit
import SnapKit
import Contacts
import ContactsUI
import TangramKit

class ViewController: UIViewController {
    
    //通讯录数据集
    var telArray:Array  = [TelModel]()
    var table:UITableView! = nil
    override func loadView(){

       super.loadView()

       let S = TGPathLayout()
       S.tg_width.equal(320)
       S.tg_height.equal(320)
       S.tg_coordinateSetting.isReverse = true
       S.tg_coordinateSetting.origin = CGPoint(x: 0.5, y: 0.2)
       S.tg_polarEquation = { 80 * (1 + cos(CGFloat($0))) } // r = a *(1 + cos(𝛉))

       for _ in 0 ..< 4
       {
           let A = UIView()
           A.tg_size(width:40,height:40)
           S.addSubview(A)

           A.backgroundColor = .green
       }

       self.view.addSubview(S)
       S.backgroundColor = .red
    }
    
//    override func viewDidLoad() {
//        super.viewDidLoad()
//        // Do any additional setup after loading the view.
//        setupUI()
//        //判断是否授权
//        let status = CNContactStore.authorizationStatus(for: .contacts)
//        if status == .notDetermined{
//            //请求授权
//            let contactStore = CNContactStore()
//            contactStore.requestAccess(for: CNEntityType.contacts, completionHandler:{(granted :Bool,error:Error?) in
//
//                if granted {
//                    print("授权成功")
//                    self.getContacts()
//                } else {
//
//                    print("用户未授权")
//                }
//
//            })
//
//        }else{
//            self.getContacts()
//        }
//
//
//    }
    
    
}

extension ViewController
{
    func getContacts() {
        // 验证授权
        // 1. 判断授权
        let status = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
        // 2. 如果授权没有请求,需要请求
        if status != .authorized {
            print("授权失败")
            return
        }
        
        //判断当前授权状态 guard 判断语句 else { do something }
        // 判读语句为false 时执行do something
        //guard status == .authorized else { return }
        
        // 获取所有联系人
        // 1.创建联系人对象
        let contactStore = CNContactStore()
        
        // 2, 使用一个方法, 遍历所有联系人
        // 作用, 根据筛选的条件, 遍历所有的联系人
        // 值获取这个参数里面提供的key对应的值, 其他的字段属性, 都不获取
        //获取Fetch,并且指定要获取联系人中的什么属性
        //2.定义要获取的属性键值
        let keys = [CNContactFamilyNameKey, CNContactGivenNameKey, CNContactNicknameKey,CNContactOrganizationNameKey, CNContactJobTitleKey,CNContactDepartmentNameKey, CNContactPhoneNumbersKey,CNContactEmailAddressesKey, CNContactPostalAddressesKey,CNContactDatesKey, CNContactInstantMessageAddressesKey]
        //创建请求对象，需要传入一个(keysToFetch: [CNKeyDescriptor]) 包含'CNKeyDescriptor'类型的数组
        let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
        
        
        //检索条件，检索所有名字中有zhang的联系人
        let predicate:NSPredicate = CNContact.predicateForContacts(matchingName: "Kate")
        //提取数据
        let contacts = try? contactStore.unifiedContacts(matching: predicate, keysToFetch: keys as [CNKeyDescriptor])
        
        
        print(contacts as Any)
        
        do {
            // 遍历联系人
            // 注意, 这种遍历, 类似于数组的遍历
            // 每执行一次block, 只会传递过来一个联系人对象
            // 而联系人对象里面的值得获取, 是根据上面 CNContactFetchRequest, 参数指定的key来的, 没写的key, 统统不获取
            
            try contactStore.enumerateContacts(with:request) { (contact: CNContact, stop) in
                //
                let givenName = contact.givenName
                print(givenName)
                // 遍历电话号码
                let phoneNums = contact.phoneNumbers
                // 每个电话号码, 包括标签和值
                for phoneNum in phoneNums {
                    let label = phoneNum.label
                    let value = phoneNum.value
                    print(label as Any, value.stringValue)
                }
                
                let model = TelModel();
                print(model.get_class_copyPropertyList())
                model.name = givenName
                model.tel = phoneNums.first?.value.stringValue
                self.telArray.append(model)
                
                //去掉联系人姓名为空或者 电话为空的数据
                if(model.name == "" || model.tel == ""){
                    self.telArray.remove(at: self.telArray.count-1)
                }
                
            }
           //在主线程中刷新数据
            DispatchQueue.main.async(execute: {
                self.table.reloadData()
                
            })
        } catch {
            
            print(error)
            return
        }
    }
    
    /// 拨打电话
    func callPhone(_ phone: String) {
        if phone.isEmpty {
            print("电话号码异常")
        } else {
            var tel = "tel://"+phone
            //去掉空格-不然有些电话号码会使 URL 报 nil
            tel = tel.replacingOccurrences(of: " ", with: "", options: .literal, range: nil);
            print(tel)
            if let urls = URL(string: tel){
                //ios 10.0以上和一下调用不同的方法拨打电话-默认都会弹框询问
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(urls, options: [:], completionHandler: {
                       (success) in
                        print("Open \(phone): \(success)")
                    })
                } else {
                    UIApplication.shared.openURL(urls)
                }
            }else{
                print("url 为空!")
            }
        }
    }

    
    
}
// MARK:- 设置UI界面相关
extension ViewController
{
    /// 设置UI界面
    func setupUI()  {
        
        //初始化table，为了简化代码，frame为全屏尺寸
        table = UITableView(frame:view.bounds, style: .plain)
        //table添加到视图上，并声明delegate和datasource
        self.view!.addSubview(table)
        table.dataSource = self
        table.delegate = self
        table.register(JSTableViewCell.self, forCellReuseIdentifier: "cellID")
    }
}
// MARK:- tableView的数据源和代理方法
// extension类似OC的category,也是只能扩充方法,不能扩充属性
extension ViewController : UITableViewDataSource,UITableViewDelegate
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return telArray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
           return 80
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:JSTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath) as! JSTableViewCell
        cell.dcLabel.text = telArray[indexPath.row].tel
        cell.title.text = telArray[indexPath.row].name
//        cell.textLabel?.text=telArray[indexPath.row].name
//        cell.telName.text = telArray[indexPath.row].name
        

        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        print("点击了:\(indexPath.row)")
        callPhone(telArray[indexPath.row].tel ?? "电话为空！")
    }
   
}

class JSTableViewCell: UITableViewCell {
    var icon = UIImageView()
    var title = UILabel()
    lazy var container = UIView()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        addSubview(container)
        addSubview(icon)
        addSubview(title)
        addSubview(dcLabel)
        container.snp.makeConstraints { (make) in
            make.edges.equalTo(self);
        }
        icon.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            make.centerY.equalToSuperview()
            // 设置icon的宽高各20个单位
            make.width.height.equalTo(container.snp.height).multipliedBy(0.6)
        }
        title.snp.makeConstraints { (make) in
            make.top.equalTo(container).offset(5)
            make.left.equalTo(icon.snp.right).offset(10)
            make.height.equalTo(30)
            make.right.equalToSuperview().offset(-10)
        }
        dcLabel.snp.makeConstraints { (make) in
            make.top.equalTo(title.snp.bottom).offset(0)
            make.left.equalTo(icon.snp.right).offset(10)
            make.bottom.equalTo(container)
            make.right.equalTo(container).offset(-10)
        }
        container.backgroundColor = UIColor.systemRed
        icon.backgroundColor = UIColor.green
        title.backgroundColor = UIColor.systemBlue
        dcLabel.backgroundColor = UIColor.systemOrange
        
        //        dcLabel.frame = CGRect(x: 20,y: 1,width: 100,height: 80);
//        dcLabel.snp.makeConstraints { (make) in
//            //            make.top.equalTo(self);
//            //            make.left.equalTo(self);
//            make.edges.equalTo(self)
//        }
        
        dcLabel.text = "赵大财博客";
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    lazy var dcLabel: UILabel = {
        let dcLabel = UILabel()
        dcLabel.text = "百度"
        dcLabel.backgroundColor = UIColor.green
        dcLabel.textAlignment = NSTextAlignment.left
        return dcLabel
    }()
}
